﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using HY.Model;
using HY.Service;
using System.Security.Claims;
using HY.Common;

namespace HY.Web
{
    /// <summary>
    /// 自定义Cookie授权事件
    /// </summary>
    public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
    {
        /// <summary>
        /// 用户信息更新时，清除认证，重新登录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            var lastModifyTime = context.Principal.FindFirstValue(SystemConst.CookieKey.LastModifyTime);
            var userId = context.Principal.FindFirstValue(SystemConst.CookieKey.UserId);

            bool userUpdate = false;
            if (lastModifyTime != null && userId != null)
            {
                SysUser sysUser = DbContext.SysUser.GetById(int.Parse(userId));
                userUpdate = DateTime.Compare(Convert.ToDateTime(lastModifyTime), sysUser.UpdateTime ?? DateTime.MinValue) <= 0;
            }

            if (userUpdate)
            {
                context.RejectPrincipal();
                await context.HttpContext.SignOutAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme);
            }
        }
    }
}
